package com.pmonitor.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import weibo4j.Oauth;
import weibo4j.Weibo;

import com.opensymphony.xwork2.ActionContext;
import com.pmonitor.util.SessionUtils;
import com.pmonitor.util.Utils;

public class OAuthAction extends BaseAction {
	/**
	 * 
	 */
	private static final long serialVersionUID = -735162401498134215L;
	public String execute(){
		HttpServletResponse resp = (HttpServletResponse) ActionContext.getContext().get(org.apache.struts2.StrutsStatics.HTTP_RESPONSE);
		HttpServletRequest req = (HttpServletRequest)ActionContext.getContext().get(org.apache.struts2.StrutsStatics.HTTP_REQUEST);
		String result = "success";
		result = doLogin(req, resp);
		return result;
	}
	
	private String doLogin(HttpServletRequest req, HttpServletResponse resp) {
		String code = req.getParameter("code");
		Oauth oauth = new Oauth();
		if(Utils.isEmptyOrNull(code)){
			String respUrl = "";
			try{
				respUrl = oauth.authorize("code");
				resp.sendRedirect(respUrl);
			}
			catch(Exception e){
				System.out.println(e);
			}
		}
		else{
			try{
				accessToken = oauth.getAccessTokenByCode(code);
				if(accessToken!=null){
					weibo = new Weibo();
					weibo.setToken(accessToken.getAccessToken());
					SessionUtils.setAccessToken(req, accessToken);
					SessionUtils.setWeibo(req, weibo);
				}
				return "success";
			}
			catch(Exception e){
				System.out.println(e);
			}
		}
	    return "success";
	}
}
